class BatchController < ApplicationController

  # lists the currently running batches
  def index
    @title1 = 'Batches'
    @url1 = '/batch/'
    @batches = Batch.find_by_sql("SELECT * FROM batches ORDER BY id DESC");
  end

  def new
    @current_revision = svn_get_current_revision
    @title1 = 'Batches'
    @url1 = '/batch/'
    @title2 = 'New'
    @url2 = '/batch/new'
  end

  def create
    current_revision = svn_get_current_revision
    
    # make sure the revision we recieved is <= the current revision
    requested_revision = params[:batch_revision].to_i
    
    if requested_revision > current_revision then
      flash[:error] = "Requested revision is greater than the HEAD revision!"
      render :action => 'new'
      return 
    end

    # create a new batch job.
    @batch = Batch.new
    
    @batch.name = Word.find(rand(Word.count-1)+1).name.to_s
    red = rand(255).to_s(16)
    blue = rand(255).to_s(16)
    green = rand(255).to_s(16)
    
    colour = '#'
    colour += '0' if red.length == 1
    colour += red
    colour += '0' if blue.length == 1
    colour += blue
    colour += '0' if green.length == 1
    colour += green
    @batch.colour = colour
    @batch.completed = 0
    @batch.description = "SVN revision #{requested_revision}, #{params[:test_suite]}"
    @batch.priority = 'medium'
    @batch.svn_revision = requested_revision
    @batch.creation_time = DateTime.now
    
    # parse test suite string.
    unless params[:test_suite].length > 0 then
      flash[:error] = "No tests specified!"
      render :action => 'new'
      return
    end
    suites = params[:test_suite].split ','
    suites.each { |s|
      # is it valid?
      suite = TestSuite.find_by_name s
      if suite.nil? then
        flash[:error] = "Unknown test: #{s}"
        render :action => 'new'
        return
      end

      # suite is valid, schedule all builds/tests.
      suite.build_types.each { |bt|
        @batch.build_runs << BuildRun.create(:build_type_id => bt.id,
                                             :status => 'pending')
      }
      
      suite.test_types.each { |tt|
        @batch.test_runs << TestRun.create(:test_type_id => tt.id,
                                           :status => 'pending')
      }
      # Fork a runner process.
      unless `ps aux` =~ /dispatcher\.rb/m then
        fork do
          `cd ./repository/ && ./dispatcher.rb`
        end
      end
    }

    @batch.save
    @architectures = Architecture.find_all
    redirect_to :action => 'show', :id => @batch.id

  end
  
  def show
    begin
      @batch = Batch.find params[:id]
    rescue
      @batch = Batch.find_by_name params[:id] if @batch.nil?
    end
    @title1 = 'Batches'
    @url1 = '/batch/'
    @title2 = @batch.name
    @url2 = "/batch/show/#{@batch.name}"
    @architectures = Architecture.find_all
  end

end
